<script setup>
import { queryProductsByTotalPopularity } from '@/apis/bestSelling.js'
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const goodList = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const finished = ref(false)

// 查询商品方法
const queryProducts = async () => {
  if (loading.value || finished.value) return

  try {
    loading.value = true
    const res = await queryProductsByTotalPopularity(
      pageNum.value,
      pageSize.value
    )

    // 添加数据安全检查
    if (res.code === 200 && res.data) {
      const list = res.data.list || [] // 添加空数组作为默认值

      // 追加数据
      goodList.value = [...goodList.value, ...list]

      // 判断是否还有更多数据
      if (pageNum.value >= (res.data.pages || 1)) {
        finished.value = true
      } else {
        pageNum.value++
      }
    } else {
      finished.value = true
      if (goodList.value.length === 0) {
        ElMessage.warning(res.msg || '暂无数据')
      }
    }
  } catch (error) {
    console.error('查询失败', error)
    ElMessage.error('加载失败，请重试')
    finished.value = true
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  queryProducts()
})
</script>

<template>
  <div class="container">
    <h2>爆款商品</h2>
    <div
      class="sub-container"
      v-infinite-scroll="queryProducts"
      :infinite-scroll-disabled="loading || finished"
      :infinite-scroll-distance="50"
    >
      <!-- 商品列表 -->
      <div class="body" v-if="goodList.length > 0">
        <goods-item
          v-for="good in goodList"
          :key="good.id"
          :good="good"
        ></goods-item>
      </div>

      <!-- 空状态 -->
      <el-empty v-else-if="!loading" description="暂无数据" />

      <!-- 加载状态 -->
      <div class="loading-status">
        <p v-if="loading" class="loading-text">
          <el-icon class="is-loading"><Loading /></el-icon>
          加载中...
        </p>
        <p v-if="finished && goodList.length > 0" class="finished-text">
          没有更多了
        </p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.sub-container {
  padding: 20px 10px;
  background-color: #fff;

  .body {
    display: flex;
    flex-wrap: wrap;
    padding: 0 10px;
  }

  .goods-item {
    display: block;
    width: 220px;
    margin-right: 20px;
    padding: 20px 30px;
    text-align: center;

    img {
      width: 160px;
      height: 160px;
    }

    p {
      padding-top: 10px;
    }

    .name {
      font-size: 16px;
    }

    .desc {
      color: #999;
      height: 29px;
    }

    .price {
      color: $priceColor;
      font-size: 20px;
    }
  }
}

.loading-status {
  text-align: center;
  padding: 20px 0;

  .loading-text {
    color: #909399;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }

  .finished-text {
    color: #909399;
    font-size: 14px;
  }
}
</style>
